<template>
  <div id="app">
    <place v-if="isRender"></place>
  </div>
</template>

<script>
import cosmo from 'cosmo-wallet-tool'
import { showToast } from '@/assets/js/utils'
import place from '@/components/place.vue'

export default {
  data() {
    return {
      isRender: false,
    }
  },

  mounted() {
    this.initWallet()
  },

  methods: {
    // 初始化钱包
    async initWallet() {
      try {
        const isWallet = await cosmo.isWallet
        const isChrome = await cosmo.isChrome
        console.log('isWallet', isWallet)
        console.log('isChrome', isChrome)
        
        if (isWallet || isChrome) {
          // 在可运行的环境内
          const result = await cosmo.getPermission()
          let permission = result && result.length !== 0

          if (permission) {
            // 已授权
            this.getFromAddress()
          } else {
            // 未授权
            permission = await cosmo.applyPermission()

            if (permission) {
              this.getFromAddress()
            }
          }
        } else {
          showToast('请在Cosmo Wallet或Chrome浏览器打开')
        }
      } catch (err) {
        console.log(err)
      }
    },

    // 获取钱包地址
    async getFromAddress() {
      try {
        const fromAddress = await cosmo.getAccount()

        if (fromAddress) {
          window.fromAddress = fromAddress
          window.toAddress = 'gx18wvaqsnlreqvj5ns5xtkqdsa0tkaf2prk0xdeh'
          this.isRender = true
        } else {
          showToast('获取钱包地址失败')
        }
      } catch (err) {
        console.log(err)
      }
    },
  },

  components: {
    place,
  },
}
</script>

<style lang="scss">
@import '@/assets/style/index.scss';

#app {
  max-width: 500px;
  margin: 0 auto;
}
</style>
